package com.kakarote.hrm.service.impl;


import com.kakarote.core.common.enums.DataAuthEnum;
import com.kakarote.core.common.enums.SystemCodeEnum;
import com.kakarote.core.entity.BasePage;
import com.kakarote.core.exception.CrmException;
import com.kakarote.core.feign.admin.service.AdminService;
import com.kakarote.core.servlet.BaseServiceImpl;
import com.kakarote.core.utils.UserUtil;
import com.kakarote.hrm.common.EmployeeHolder;
import com.kakarote.hrm.constant.MenuIdConstant;
import com.kakarote.hrm.entity.BO.QueryEmployeeDataBo;
import com.kakarote.hrm.entity.PO.HrmDept;
import com.kakarote.hrm.entity.PO.HrmEmployeeData;
import com.kakarote.hrm.entity.PO.HrmEmployeeDataIntegrity;
import com.kakarote.hrm.entity.VO.EmployeeDataIntegrityVo;
import com.kakarote.hrm.mapper.HrmEmployeeDataIntegrityMapper;
import com.kakarote.hrm.service.IHrmDeptService;
import com.kakarote.hrm.service.IHrmEmployeeDataIntegrityService;
import com.kakarote.hrm.service.IHrmEmployeeDataService;
import com.kakarote.hrm.utils.EmployeeUtil;
import io.seata.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 员工数据完整度 服务实现类
 * </p>
 *
 * @author guomenghao
 * @since 2021-04-14
 */
@Service
public class HrmEmployeeDataIntegrityImpl extends BaseServiceImpl<HrmEmployeeDataIntegrityMapper, HrmEmployeeDataIntegrity> implements IHrmEmployeeDataIntegrityService {

    @Autowired
    private HrmEmployeeDataIntegrityMapper employeeDataIntegrityMapper;

    @Autowired
    private IHrmDeptService hrmDeptService;

    @Autowired
    private IHrmEmployeeDataService employeeDataService;

    @Autowired
    private IHrmDeptService deptService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private EmployeeUtil employeeUtil;

    @Override
    public BasePage<EmployeeDataIntegrityVo> queryEmployeeDataIntegrity(QueryEmployeeDataBo queryEmployeeDataBo) {
        if(StringUtils.isEmpty(queryEmployeeDataBo.getTotalDate()) || queryEmployeeDataBo.getDeptId() == null){
            throw new CrmException(SystemCodeEnum.SYSTEM_NO_VALID);
        }
        DateTimeFormatter yearMonthFormatter = DateTimeFormatter.ofPattern("yyyy-MM");
        YearMonth yearMonth = YearMonth.parse(queryEmployeeDataBo.getTotalDate(), yearMonthFormatter);
        // 获取当前日期
        YearMonth currentYearMonth = YearMonth.now();
        //数据完整度检索日期
        LocalDate integrityDate;
        if (yearMonth.equals(currentYearMonth)) {
            integrityDate = LocalDate.now().minusDays(1);
        }else {
            integrityDate = yearMonth.atDay(yearMonth.lengthOfMonth());
        }
        queryEmployeeDataBo.setIntegrityDate(integrityDate.toString());
        if (queryEmployeeDataBo.getDeptId() != null){
            //部门检索
            List<Long> deptIds = hrmDeptService.selectChildrenDeptIds(queryEmployeeDataBo.getDeptId());
            queryEmployeeDataBo.setChildrenDeptIdList(deptIds);
            queryEmployeeDataBo.setDeptId(null);
        }

        List<Integer> dataAuthTypeList = adminService.queryDataTypeList(UserUtil.getUserId(), MenuIdConstant.DEPT_MENU_ID).getData();
        if (EmployeeHolder.isHrmAdmin() || dataAuthTypeList.contains(DataAuthEnum.ALL.getValue())) {
        }else {
            if (!dataAuthTypeList.isEmpty()) {
                Set<Long> deptIds = employeeUtil.queryDataAuthDeptId(dataAuthTypeList, MenuIdConstant.DEPT_MENU_ID);
                deptIds.add(-1L);
                queryEmployeeDataBo.setAuthDeptIds(deptIds);
            }
        }
        BasePage<EmployeeDataIntegrityVo> employeePage = employeeDataIntegrityMapper.queryEmployeeDataIntegrity(queryEmployeeDataBo.parse(), queryEmployeeDataBo);
        List<EmployeeDataIntegrityVo> list = employeePage.getList();
        if (list != null && !list.isEmpty()){
            // 获取所有部门信息
            List<HrmDept> allDeptList = deptService.lambdaQuery().list();
            Map<Long, HrmDept> deptMap = new HashMap<>();
            if (allDeptList != null && !allDeptList.isEmpty()){
                deptMap = allDeptList.stream().collect(Collectors.toMap(HrmDept::getDeptId, Function.identity()));
            }
            // 获取员工自定义字段
            List<Long> empIds = list.stream().map(EmployeeDataIntegrityVo::getEmployeeId).collect(Collectors.toList());
            List<HrmEmployeeData> employeeDataList = employeeDataService.lambdaQuery().in(HrmEmployeeData::getEmployeeId, empIds).list();
            Map<Long, List<HrmEmployeeData>> employeeDataGroup = employeeDataList.stream().collect(Collectors.groupingBy(HrmEmployeeData::getEmployeeId));
            for (EmployeeDataIntegrityVo emp : list) {
                Long empId = emp.getEmployeeId();
                if (employeeDataGroup.containsKey(empId)) {
                    List<HrmEmployeeData> fieldList= employeeDataGroup.get(empId);
                    Map<String, String> fieldMap = fieldList.stream().collect(Collectors.toMap(HrmEmployeeData::getFieldName, item -> Optional.ofNullable(item.getFieldValue()).orElse(""), (v1, v2) -> v2));
                    emp.setJobLevel(fieldMap.get("job_level"));
                    emp.setJobTitle(fieldMap.get("job_title"));
                    emp.setPolId(fieldMap.get("pol_id"));
                    emp.setPostStatus(fieldMap.get("post_status"));
                    emp.setWorkForms(fieldMap.get("work_forms"));
                    HrmDept hrmDept = deptMap.get(emp.getDeptId());
                    if (hrmDept != null){
                        emp.setDeptName(hrmDept.getName());
                    }
                    HrmDept org = deptMap.get(emp.getOrgId());
                    if (org != null){
                        emp.setOrgName(org.getName());
                    }
                }
            }
        }
        return employeePage;
    }
}
